package link.chengguo.orangemall.service.ams.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import link.chengguo.orangemall.ams.entity.AmsAgent;
import link.chengguo.orangemall.ams.entity.AmsAgentBlanceLog;
import link.chengguo.orangemall.ams.mapper.AmsAgentMapper;
import link.chengguo.orangemall.service.ams.IAmsAgentBlanceLogService;
import link.chengguo.orangemall.service.ams.IAmsAgentService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;

/**
 * @author yzb
 * @date 2019-12-21
 */
@Service
public class AmsAgentServiceImpl extends ServiceImpl
        <AmsAgentMapper, AmsAgent> implements IAmsAgentService {

    @Resource
    private AmsAgentMapper amsAgentMapper;
    @Resource
    private IAmsAgentBlanceLogService amsAgentBlanceLogService;

    @Transactional
    @Override
    public boolean addAgentBalanceForSettlement(Long orderId,String cityCode, BigDecimal money) {
        //根据cityCode获取代理信息
        AmsAgent agent=getAgentByCityCode(cityCode);
        if (agent==null){
            return false;
        }
        //代理增加可用余额和总余额。
        agent.setBalance(agent.getBalance().add(money));
        agent.setBalanceWithdraw(agent.getBalanceWithdraw().add(money));
        amsAgentMapper.updateById(agent);
        //新增代理账户余额记录
        AmsAgentBlanceLog log=new AmsAgentBlanceLog();
        log.setCityCode(cityCode);
        log.setCreateTime(new Date());
        log.setPrice(money);
        //0-订单结算，1-提现申请，2-申请通过，2-申请失败
        log.setType(0);
        log.setNote("订单佣金收入："+orderId);
        amsAgentBlanceLogService.save(log);
        return true;
    }

    @Override
    public AmsAgent getAgentByCityCode(String cityCode) {
        return amsAgentMapper.selectOne(new QueryWrapper<AmsAgent>().eq("city_code",cityCode));
    }
}
